/**
 * 获取openid
 * 获取token
 */
const { appId, secret } = require('@config').wxConfig
const axios = require('axios')
const { AuthFailedException } = require('@core/http-exception.js')
const { User } = require('@model/user.js')
const { generateToken } = require('@core/util.js')
class WxManager {
  static async byCodeToGetToken(code) {
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${secret}&js_code=${code}&grant_type=authorization_code`
    const res = await axios.get(url)
    console.log('res', res);
    if (res.status !== 200) {
      throw new AuthFailedException('授权失败')
    }
    const errmsg = res.data.errmsg
    const errcode = res.data.errcode
    console.log('errmsg', errmsg);
    console.log('errcode', errcode);
    if (errmsg) {
      throw new AuthFailedException(errmsg, errcode)
    }
    const openId = res.data.openid
    if (!openId) {
      throw new AuthFailedException('openId获取失败')
    }
    // 数据库查找openid是否存在
    let user = await User.findOne({
      where: {
        openId
      }
    })
    if (!user) {
      user = await User.create({
        openId
      })
    }
    return generateToken(user.id, 8)
  }
}

module.exports = {
  WxManager
}